package com.qikux.utils;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.Sign;
import cn.hutool.crypto.asymmetric.SignAlgorithm;
import com.qikux.exception.DataAccessException;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class RSAUtils {
    /**
     * 公钥
     */
    public static final String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCerl7rDI7hgQK1NTyGY/Ep/zQHDTsYAyrPt0WuVie25CCznn9F2IeteVyJqFuzrI9msv7AURg3NA86YmfrB/ThsxPzQIBukRzqamDbxh99u4/VByEBZS5hHaqdEFca3mdrWbNInIWorNp12dRRm351D/v6c1kMI/m6Ymk+zeLygwIDAQAB" ;

    /**
     * 私钥
     */
    public static final String privateKey = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAJ6uXusMjuGBArU1PIZj8Sn/NAcNOxgDKs+3Ra5WJ7bkILOef0XYh615XImoW7Osj2ay/sBRGDc0DzpiZ+sH9OGzE/NAgG6RHOpqYNvGH327j9UHIQFlLmEdqp0QVxreZ2tZs0ichais2nXZ1FGbfnUP+/pzWQwj+bpiaT7N4vKDAgMBAAECgYANU0hORcoz3rEbBYL1KCxm4fL9CpvlStLMCbB00PBZ1/N1EgDPHT1bkH74YmZ9AqcyMSLahJTbgegrd3sRjiP+s6JoC2S/w1MvSn5BBpb5qpnsJOwHGolKrV1/6zDzjREs2z4u5hJ80PpHN0Qj1/aFMSe3qJdhEDR/fVEndYHfJQJBAPPwl1bfshrROshArtT+drKAzR/cf9IQ0P40gxiiHQ7gAovuGWzT1hzsPAL3Z6do4BG6S09UUWT7WP/AoydgudUCQQCmhrVlKQsp2Wobaeb9RQTSg8Y0/NLzgE5jgXwPh3bj/ELB9BDSpRsJGZfMnOcoX9xRLOCAvv65nkUE8h0Mzg73AkAgHHSfj/TPCOnXAITDLvgLCV93KTx+N457WAhFztlKYvyS1PXt2Hjf98zyiwTPCcQtMTvGpo/MXjXZ/M69WUM9AkAG3E3k2QgItVhVwMsvbASC18L2s+PM/GA+YTtHOIGBawclDnUS+JJgkZlbaKttUmW1QnANXdEIvKiDR6ZCvMqJAkAT3rZOqvxqhws6fnkCuO8sK7/2dov8h6+X09Jl3++OhpUfCbSjUFqICndUfTJhHm8qOy06sU6WPtAoIzcmP2ka" ;

    
    private static final Sign signV = SecureUtil.sign(SignAlgorithm.MD5withRSA, privateKey, publicKey);
    /**
     * 将 message 进行 签名 
     * @param message
     * @return
     */
    public static String sign(String message)  {
        // 调用 sign 进行签名
        byte[] sign = signV.sign(message.getBytes(StandardCharsets.UTF_8));
        // 使用 base64编码
        try{
            return URLEncoder.encode(Base64.getEncoder().encodeToString(sign), "UTF-8");
        }catch (Exception e) {
            throw new DataAccessException(e);
        }
    }

    /**
     * 数字认证
     * @param message
     * @param sign
     * @return
     */
    public static boolean verify(String message,  String sign) {
        // 使用 base64解密 sign
        byte[] $sign = Base64.getDecoder().decode(sign);
        return signV.verify(message.getBytes(StandardCharsets.UTF_8) , $sign) ;
    }

}
